package edu.stanford.prpl.impl.app.xmlrpc;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcSunHttpTransport;
import org.apache.xmlrpc.client.XmlRpcTransport;
import org.apache.xmlrpc.client.XmlRpcTransportFactoryImpl;

import edu.stanford.prpl.common.SimpleLRUCache;

/**
 * XmlRpcSunHttpTransportFactory is not thread-safe and fails if more than one threads makes a request via single
 * connection. PrivateXmlRpcHttpTransportFactory returns a new XmlRpcTrasport object per thread.
 * 
 * @author sseong
 * 
 */
public class PrplXmlRpcHttpTransportFactory extends XmlRpcTransportFactoryImpl {

	private final int MAX_CONNECTION = 15;	
	private SimpleLRUCache<Long, XmlRpcTransport> simpleLRU;
	
	public PrplXmlRpcHttpTransportFactory(XmlRpcClient pClient) {
		super(pClient);
		this.simpleLRU = new SimpleLRUCache<Long, XmlRpcTransport>(MAX_CONNECTION);
	}

	public XmlRpcTransport getTransport() {
		long id = Thread.currentThread().getId();
		XmlRpcTransport xmlRpcTransport = simpleLRU.get(id);
		if (xmlRpcTransport == null) {
			xmlRpcTransport = new XmlRpcSunHttpTransport(this.getClient());
			simpleLRU.put(id, xmlRpcTransport);
		}
		return xmlRpcTransport;
	}

	// private final XmlRpcSunHttpTransport HTTP_TRANSPORT;
}
